package controllers;

import java.util.Set;

import javax.validation.ConstraintViolation;

import models.About;

import org.codehaus.jackson.node.ObjectNode;

import play.data.validation.Validation;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.With;

@With(ApiSecure.class)
public class ApiAbouts extends Controller {

    public static Result create() {
        ObjectNode result = Json.newObject();

        try {
            About about = Json.fromJson(request().body().asJson(), About.class);
            Set<ConstraintViolation<About>> errors = Validation.getValidator().validate(about);
            if (errors.isEmpty()) {
                about.save();
                result = (ObjectNode) Json.toJson(about);
            } else {
                ObjectNode errorsJson = Json.newObject();
                for (ConstraintViolation<About> error : errors) {
                    errorsJson.put(error.getPropertyPath().toString(), error.getMessageTemplate());
                }
                result.put("errors", errorsJson);
                result.put("error", "Error on create");
            }
        } catch (Exception e) {
            result.put("error", "Error on create");
        }

        return ok(result);
    }

    public static Result readAll() {
        return ok(Json.toJson(About.find.all()));
    }

    public static Result read(Long id) {
        ObjectNode result = Json.newObject();
        About about = About.find.byId(id);

        if (about == null) {
            result.put("error", "No About with this id");
        } else {
            result = (ObjectNode) Json.toJson(about);
        }

        return ok(result);
    }

    public static Result update() {
        About about = Json.fromJson(request().body().asJson(), About.class);
        ObjectNode result = Json.newObject();

        try {
            about.update();
            result = (ObjectNode) Json.toJson(about);
        } catch (Exception e) {
            result.put("error", "Error on update");
        }

        return ok(result);
    }

    public static Result delete(Long id) {
        ObjectNode result = Json.newObject();
        About about = About.find.byId(id);

        try {
            if (about == null) {
                result.put("error", "No About with this id");
            } else {
                about.delete();
                result.put("message", "About deleted");
            }
        } catch (Exception e) {
            result.put("error", "Error on delete");
        }

        return ok(result);
    }

}
